<?php

/**
 * @author chenshubo
 * 订单支付接口模型
 */
namespace App\Service\OrderService\OrderInterfaceService;

use App\Service\BaseService;
use App\Model\PssModel\OrderSupplier;
use App\Model\PssModel\OrderSupplierGoods;
use App\Model\CommodityModel\SupplierCompany;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use App\Service\AppService\PushOrderSettleMentService;
use App\Service\VendorClient\OrderPayDeclareService\BmDeclareServiceApi\BmDeclareServiceApiClient;
use App\Service\OrderService\OrderSupplierEventLogMessageService AS OSELMS;
use App\Service\Volidate\OrderCreateVolidate;
use App\Service\DeclareService\WayBillDecareService;
class OrderPay extends BaseService
{ 
    /**
     * 有支付接口供应商
     * @var array
     */
    public $payApiSupplier = [
        'houniao'       => '候鸟',
        //'shophd'        => '海带',
        'shophhg'       => '好嗨购关务',
        'fuzhougw'      => '福州关务',
        'shopqs'        => '乾盛关务',
        'shopfjyl'      => '福建优联',
        'shopfjldtgw'   => '福建利达通',
        'shophzg'       => '花之冠关务'
    ];

    //余外
    CONST YW_ORDER_TYPE=9;
    CONST YW_ORDER_TYPE_ARR=[9,10];
    
    /**
     * 新版本支付接口
     * @param array $param
     */
    public function index( $param = [] )
    {
        if( empty($param['requestData']) ) {
            return Normal::returnCode(Normal::FAIL,"requestData参数不能为空");
        }
        
        $requestData = $param['requestData'];
        if( empty($requestData['orderSn']) ) {
            return Normal::returnCode(Normal::FAIL,"orderSn订单号不能为空");
        }
        
        if( !isset($requestData['order_type']) && empty($requestData['paySerial']) ) {
            return Normal::returnCode(Normal::FAIL,"paySerial支付单号不能为空");
        }
        
        //判断是否是子订单发起取消动作
        if( isset($requestData['isSingleOrder']) && $requestData['isSingleOrder'] == 1 && empty($requestData['orderNo']) ) {
            return Normal::returnCode(Normal::FAIL,"供应商订单号orderNo不能为空");
        }
        //判断是否有运单申报
        if( isset($requestData['IsTransDeclare']) && (int)$requestData['IsTransDeclare'] == 1) {
            if(!isset($requestData['logisticNo']) or empty($requestData['logisticNo'])){
                return Normal::returnCode(Normal::FAIL,"物流公司申报运单号logisticNo不能为空");
            }
            if(!isset($requestData['logisticCode']) or empty($requestData['logisticCode'])){
                return Normal::returnCode(Normal::FAIL,"物流公司海关备案编码logisticCode不能为空");
            }
            if(!isset($requestData['logisticName']) or empty($requestData['logisticName'])){
                return Normal::returnCode(Normal::FAIL,"物流公司海关备案名称logisticName不能为空");
            }
            if(!isset($requestData['logisticWayBillContent']) or empty($requestData['logisticWayBillContent'])){
                return Normal::returnCode(Normal::FAIL,"物流公司面单信息(原始响应JSON报文)logisticWayBillContent不能为空");
            }
        }
        //接收申报基础信息
        $requestData['paySerial']           = $requestData['paySerial'];         //支付流水号
        $requestData['payCommanyName']      = $requestData['payCommanyName'] ?? '';//支付企业名称
        $requestData['payCommanyCode']      = $requestData['payCommanyCode'] ?? '';//支付企业海关编码
        $requestData['enterpriseNum']       = $requestData['enterpriseNum'] ?? '';//电商平台企业编号
        $requestData['enterpriseName']      = $requestData['enterpriseName'] ?? '';//电商平台名称
        $requestData['payTime']             = $requestData['payTime'] ?? '';//支付时间
        $requestData['payWay']              = $requestData['payWay'] ?? '';//支付方式：(1-摩宝，2-快钱，3-通联，4-新生支付)
        $requestData['payDecarleResponse']  = $requestData['payDecarleResponse'] ?? '';//支付申报原始响应
        $requestData['payDecarleRequest']   = $requestData['payDecarleRequest'] ?? '';//支付申报请求
        $requestData['IsTransDeclare']      = isset($requestData['IsTransDeclare']) ? (int)$requestData['IsTransDeclare'] : 0;//是否运单申报
        $requestData['logisticNo']          = $requestData['logisticNo'] ?? '';//物流公司申报运单号
        $requestData['logisticCode']        = $requestData['logisticCode'] ?? '';//物流公司海关备案编码
        $requestData['logisticName']        = $requestData['logisticName'] ?? '';//物流公司海关备案名称
        $requestData['logisticWayBillContent'] = $requestData['logisticWayBillContent'] ?? '';//物流公司面单信息(原始响应JSON报文)
        $requestData['idCardFrontImage']    = $requestData['IdCardFrontImage'] ?? '';//CC直邮请求
        $requestData['idCardBackImage']     = $requestData['IdCardBackImage'] ?? '';//CC直邮请求

        //根据原始订单号查询商户的
        $orderSn = checkFields($requestData['orderSn']);
        if( $orderSn != $requestData['orderSn'] ) {
            return Normal::returnCode(Normal::FAIL,"orderSn订单号不能包含");
        }

        $param['requestData'] = $requestData;
        $res = $this->getSupplierOrderLists($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $res['data']['order'] = $param['requestData'];
        $res['data']['binfo'] = $param['binfo'];
        //判断是否是子订单发起取消动作
        if( isset($requestData['isSingleOrder']) && $requestData['isSingleOrder'] == 1 ) {
            $orderInfo      = current($res['data']['supplierOrderList']);
            $suppplierList  = $res['data']['suppplierList'];
            $orderGoodsList = $res['data']['newOrderGoods'];
            return $this->singleOrderPay([
                'companyInfo'   => $suppplierList[$orderInfo['company_id']],
                'supplierOrder' => $orderInfo,
                'orderGoods'    => $orderGoodsList[$orderInfo['id']],
                'order'         => $res['data']['order'],
                'binfo'         => $res['data']['binfo']
            ]);
        }
        
        $res['data']['serviceClass'] = static::class;
        $res['data']['serviceMethod'] = "singleOrderPay";
        $res = TaskWorker::instance()->addTask($res['data'],'singleOrder');
        $message = implode(",", array_column($res,'msg'));
        $code = array_column($res, 'code');
        if( in_array('0', $code) ) {
            return Normal::returnCode(Normal::FAIL,$message);
        }
        return Normal::returnCode(Normal::SUC,"处理完成；【{$message}】");
    }
    
    /**
     * 开始单个订单进行支付
     * @param array $param
     */
    public function singleOrderPay( $param = [] )
    {
        if( empty($param['companyInfo']) || empty($param['supplierOrder']) || empty($param['orderGoods']) || empty($param['order']) || empty($param['binfo']) )
        {
            return Normal::returnCode(Normal::FAIL,"except param companyInfo or supplierOrder or orderGoods or order or binfo");
        }
        
        $companyInfo    = $param['companyInfo'];
        $company_code   = $companyInfo['company_code'];
        $supplierClass  = ucFirst( $companyInfo['OrderDockMode'] == 1 ? 'normal' : $companyInfo['company_code'] );
        $is_third_supplier = $companyInfo['OrderDockMode'] == 0 ? 1 : 0;
        $serviceClass   = "App\\Service\\OrderService\\OrderRouteService\\{$supplierClass}";
        if( !class_exists($serviceClass) )
        {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} not existed");
        }
        
        $requestMethod = 'orderPay';
        if( !method_exists($serviceClass,$requestMethod) )
        {
            return Normal::returnCode(Normal::FAIL,"{$serviceClass} {$requestMethod} methods not existed");
        }
        
        $supplierOrder = $param['supplierOrder'];
        $orderGoods    = $param['orderGoods'];
        $order         = $param['order'];
        $binfo         = $param['binfo'];
        
        //如果是子订单做了拆支付单
        if( $supplierOrder['order_type'] == 1 && isset($order['orderDeclareList']) ) {
            $order = $param['order'] = $order['orderDeclareList'][$supplierOrder['supplier_dsn']];
        }
        
        //统一使用科技公司mobao进行刷单支付（下游未申报支付单，上游又需要申报好支付单）
        $isUserPayDeclare  = ( $supplierOrder['is_pay_declare'] == 1 || $supplierOrder['order_type'] == 1 ) ? true : false ;
        $isUserPayDeclare  = $companyInfo['PayDeclare'] == 1 && !$isUserPayDeclare ? true : false;
        $supplierOrder['isUserPayDeclare'] = $isUserPayDeclare;
        if( !$isUserPayDeclare ) 
        {
            //下游已申报支付单
            if( $supplierOrder['is_pay_declare'] == 1 ) 
            {
                if( empty($order['payCommanyCode'])) {
                    return Normal::returnCode(Normal::FAIL,"payCommanyCode支付企业编码不能为空");
                }
                
                if( empty($order['payCommanyName'])) {
                    return Normal::returnCode(Normal::FAIL,"payCommanyName支付企业名称不能为空");
                }
            }
            
            //下游已申报订单
            if( $supplierOrder['is_order_declare'] == 1 ) {
                if( empty($order['enterpriseNum'])) {
                    return Normal::returnCode(Normal::FAIL,"enterpriseNum电商平台企业编号");
                }
                
                if( empty($order['enterpriseName'])) {
                    return Normal::returnCode(Normal::FAIL,"enterpriseName电商平台名称");
                }
            }
        }
        
        //此处调用物流公司服务接口
        $_result = WayBillDecareService::instance()->upload($binfo, $order,$supplierOrder,$orderGoods,$companyInfo);
        if( $_result['code'] != Normal::SUC ) {
            return $_result;
        }
        
        try 
        {
            OrderSupplier::instance()->startTrans();
            $res = $this->orderPayChange([
                'orderSupplier' => $supplierOrder,
                'order'         => $order,
                'companyInfo'   => $companyInfo,
                'binfo'         => $binfo,
            ]);
            
            if( $res['code'] != Normal::SUC ) {
                OrderSupplier::instance()->rollback();
                return $res;
            }
            
            $param['mode'] = PushOrderSettleMentService::SETTLEMENT_MODE_PAY;
            $param['apiBody'] = $companyInfo['apiBody'];
            
            //写入结算表标识
            $isAddSettleMentFlag = false;
            
            $order_supplier_id   = (string)$supplierOrder['id'];
            
            if( $companyInfo['PayDeclare'] == 1 && $supplierOrder['is_pay_declare'] != 1 && $supplierOrder['order_type'] == 0 )
            {
                return Normal::returnCode(Normal::FAIL,"下游已申报支付单情况下，不允许再次申报支付单!");
                //统一使用科技公司mobao进行刷单支付(云仓商场除外)
                OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_DECLARE_APPLY, "支付单发起申报");
                $res = BmDeclareServiceApiClient::instance()->OrderApply($param);//支付单申报
                $declare_result = json_encode($res,JSON_UNESCAPED_UNICODE);
                OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_DECLARE_APPLY, "支付单申报回调【{$declare_result}】");
            
            }
            else if( $companyInfo['OrderDeclare'] == 1 && $supplierOrder['is_order_declare'] != 1 )
            {
                return Normal::returnCode(Normal::FAIL,"当前订单需要去申报订单数据，此功能暂时不再进行受理!");
                //需要中台进行订单申报
                OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_DECLARE_APPLY, "订单发起申报");
                $res = OrderSupplier::instance()->orderPush([//订单申报
                    'supplierOrder' => $supplierOrder,
                    'orderItem'     => $orderGoods,
                    'companyInfo'   => $companyInfo,
                    'order'         => $order,
                    'binfo'         => $binfo,
                ]);
                $declare_result = json_encode($res,JSON_UNESCAPED_UNICODE);
                OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_DECLARE_APPLY, "支付单申报回调【{$declare_result}】");
            
            }
            else
            {
                //写入结算中间表
                if( $supplierOrder['is_channel_settlement'] == 1 || $supplierOrder['is_supplier_settlement'] ==1 ) {
                    $isAddSettleMentFlag = true;
                    $res = PushOrderSettleMentService::instance()->addOrderSettleMentLog($param);
                    if( $res['code'] != Normal::SUC ) {
                        OrderSupplier::instance()->rollback();
                        return $res;
                    }
                }
            
                //上游不需要支付单和订单申报,直接推送供应商订单
                $is_push_supplier = 1;
                
                //因为供应商路由里面加了 new exception 抛出异常，这里需要进行二次捕捉问题，不能直接抛到事务以外去回滚了
                try {
                    $res = $serviceClass::instance()->$requestMethod($param);
                } catch ( \Throwable $th ) {
                    $res = Normal::returnCode(Normal::FAIL,"调用系统路由失败[{$th->getMessage()}]");
                }
            }
            
            //返回原始订单信息
            /* $res['data']['orderItem']['orderSn'] = $supplierOrder['order_sn'];
            $res['data']['orderItem']['orderNo'] = $supplierOrder['supplier_csn']; */
            
            //支付或者推送订单接口成功
            if( $res['code'] == Normal::SUC ) 
            {
                //推送第三方订单成功之后，回写第三方订单号
                if( isset($res['data']['thirdpart_order_sn']) ) {
                    $resId = OrderSupplier::instance()->where('id',$supplierOrder['id'])->update([
                        'thirdpart_order_sn' => $res['data']['thirdpart_order_sn'],
                        'md' => time(),
                    ]);
                    if( !$resId ) {
                        OrderSupplier::instance()->rollback();
                        return Normal::returnCode(Normal::FAIL,"更新第三方供应商订单号失败");
                    }
                }
            
                //提交事务之前，写入订单行为日志,排除大平台订单日志
                if( !isset(OrderCreateVolidate::$sensitive_user[$binfo['user_tag']]) )
                {
                    //订单支付成功
                    OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_PAY, "订单支付");
            
                    //订单推送供应商
                    if( $is_third_supplier == 1 ) {
                        OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_PUSH_SUPPLIER_PASS, "订单供应商推送成功");
                    }
            
                    //订单发起结算
                    if( $isAddSettleMentFlag ) {
                        OSELMS::instance()->publish($order_supplier_id,OSELMS::EVENT_TYPE_ORDER_SETTLEMENT_PAY, "订单发起结算");
                    }
                }
            
                OrderSupplier::instance()->commit();
                return $res;
            }
            
            //提交事务之前，写入订单行为日志,排除大平台订单日志
            if( isset($is_push_supplier) && !isset(OrderCreateVolidate::$sensitive_user[$binfo['user_tag']]) )
            {
                $result = OSELMS::instance()->publish((string)$supplierOrder['id'],OSELMS::EVENT_TYPE_ORDER_PUSH_SUPPLIER_FAIL, "供应商订单推送失败");
                if( $result['code'] != Normal::SUC )
                {
                    OrderSupplier::instance()->rollback();
                    return Normal::returnCode(Normal::FAIL,"系统内部异常，请稍后再试【{$result['msg']}】");
                }
            }
            
            //如果是写入了结算表标识，推送供应商失败的情况下，需要恢复临时结算数据
            if( $isAddSettleMentFlag ) {
                PushOrderSettleMentService::instance()->removeOrderSettleMentLog($param);
            }
            
            //路由模式处理多多和京东捞单池问题
            if( $binfo['is_router_user'] == 1 && !empty($binfo['user_tag']) && isset(OrderCreateVolidate::$retry_pay_user[$binfo['user_tag']]) ) {
                OrderSupplier::instance()->rollback();
                $errorMsg = $result['msg'] ?? '支付回传关务接口请求失败,请稍后重新发起重推订单操作！';
                return Normal::returnCode(Normal::FAIL,"系统内部异常，请稍后再试【{$errorMsg}】");
            }
            
            //写入支付失败数据
            $param['message'] = $res['msg'];
            $isReturnSuccess = $this->orderChangeRecover($param);
            OrderSupplier::instance()->commit();
            
            //如果操作成功则返回成功
            if( $isReturnSuccess ) {
                return Normal::returnCode(Normal::SUC,$res['msg'],$res['data']);
            }
            
            return Normal::returnCode(Normal::FAIL,$res['msg'],$res['data']);
        } catch ( \Throwable $th) {
            OrderSupplier::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,"支付处理失败，异常原因[{$th->getMessage()}]");
        }
    }
    
    /**
     * 获取供应商列表
     * @param array $param
     */
    public function getSupplierOrderLists( $param = [] )
    {
        $binfo = $param['binfo'];
        $bid = $binfo['bid'];
        $query = OrderSupplier::instance()
        ->select(OrderSupplier::instance()->order_fields)
        ->where('bid',$bid)
        ->where('order_sn',$param['requestData']['orderSn'])
        ->whereIn('order_status',[0,200]);
        
        if( !empty($param['requestData']['orderNo']) ) {
            $query->where('supplier_csn',$param['requestData']['orderNo']);
        }
        
        $supplierOrderList = $query->get()->toArray();
        if( empty($supplierOrderList) ) {
            return Normal::returnCode(Normal::FAIL,"当前订单不存在或已支付");
        }
        
        //获取订单商品
        $osids  = array_column($supplierOrderList,'id');
        $orderGoods = OrderSupplierGoods::instance()
        ->select(OrderSupplierGoods::instance()->goods_fields)
        ->where('bid',$bid)
        ->whereIn('order_id',$osids)
        ->get()
        ->toArray();
        
        if( empty($orderGoods) ) {
            return Normal::returnCode(Normal::FAIL,"获取订单数据失败");
        }
        
        $newOrderGoods = [];
        foreach ($orderGoods as $item ) {
            $newOrderGoods[$item['order_id']][] = $item;
            unset($item);
        }
        
        //获取供应商清单信息
        $companyIds = array_unique(array_column($supplierOrderList,'company_id'));
        $SupplierCompanyLists = SupplierCompany::instance()->getSupplierListByIds($companyIds);
        $SupplierCompanyLists = array_column($SupplierCompanyLists, null,'company_id');
        $IsChannelSettlements = array_column($supplierOrderList,'is_channel_settlement');
        $currentOrder = current($supplierOrderList);
        //云仓商城、京东、拼多多、唯品会跳过验证
        if( in_array(1,$IsChannelSettlements) ) {
            //账户余额度
            $total_balance_settlement_money = $binfo['total_balance_settlement_money'];
            if( $binfo['settlement'] == 1 ) {//预付款  $totalSettlementMoney <= $binfo['total_balance_settlement_money']
                //结算总金额
                $totalSettlementMoney = $this->getSettleMentTotalMoney($supplierOrderList, $newOrderGoods);
                if( bcsub((string)$total_balance_settlement_money, $totalSettlementMoney,2) < 0 ) {
                    return Normal::returnCode(Normal::FAIL,"当前预付款账户金额不足，请联系相应业务人员进行充值！");
                }
            } else {//账期商户
                if( bcadd((string)$binfo['settlement_warn_money'],(string)$total_balance_settlement_money,2) < 0 ) {
                    return Normal::returnCode(Normal::FAIL,"账期额度不足，请联系相应业务人员进行充值！");
                }
            }
        }
        
        return Normal::returnCode(Normal::SUC,"订单数据获取成功",[
            'supplierOrderList' => $supplierOrderList,
            'newOrderGoods' => $newOrderGoods,
            'suppplierList' => $SupplierCompanyLists,
        ]);
    }
    
    /**
     * 计算真实结算价格
     * @param array $orderList
     * @param array $orderGoodsList
     */
    public function getSettleMentTotalMoney( $orderList , $orderGoodsList )
    {
        $totalSettlementMoney = 0.00;
        foreach ($orderList as $orderInfo ) 
        {
            if ($orderInfo['is_channel_settlement']!=1){
                continue;
            }
            $goodsList      = $orderGoodsList[$orderInfo['id']];
            $user_taxAmount = $total_settlement_price = 0.00;
            foreach ($goodsList as $v ) 
            {
                $quantity               = $v['quantity'];
                $tax_rate               = $v['tax_rate'];
                $price                  = $v['price'];
                $has_rate               = $v['has_rate'];
                
                //商户结算价
                $settlement_price       = $v['settlement_price'];
                $total_settlement_price = bcadd((string)$total_settlement_price,bcmul((string)$v['settlement_price'], (string)$quantity,2),2);
                
                //税费 = 商品售价 * 税率
                $tax_rate_all           = bcadd((string)$tax_rate,'1.0000',4);
                
                //商品不含税价格
                $noTaxPrice             = bcdiv((string)$price,(string)$tax_rate_all,2);
                $userTaxAmount          = bcsub((string)$price,(string)$noTaxPrice,2);
                $userTaxAmount          = bcmul((string)$userTaxAmount, (string)$quantity,2);
                
                //是否含税,含税不计算税金
                if( $has_rate == 1 ) {
                    $user_taxAmount     = bcadd((string)$user_taxAmount,(string)0,2);
                } else {
                    $user_taxAmount     = bcadd((string)$user_taxAmount,(string)$userTaxAmount,2);
                }
                unset($v);
            }
            
            //商品结算价 + 税费 + 实际运费
            $singleOrderMoney = bcadd((string)$user_taxAmount,(string)$total_settlement_price,2);
            $singleOrderMoney = bcadd((string)$singleOrderMoney, (string)$orderInfo['total_template_delivery'],2);
            $totalSettlementMoney += bcadd((string)$totalSettlementMoney,(string)$singleOrderMoney,2);
            unset($orderInfo);
        }
        return $totalSettlementMoney;
    }
    

    /**
     * 支付状态修改
     * @param array $param
     */
    public function orderPayChange( $param = [] )
    {
        $order              = $param['order'];
        $orderSupplier      = $param['orderSupplier'];
        $time               = time();
        $companyInfo        = $param['companyInfo'];
        $company_code       = $companyInfo['company_code'];
        $binfo              = $param['binfo'];
        
        //组装支付修改数据
        $payTime = $order['payTime'] ?? '';
        $editSupplierOrder = [
            'pay_way'               => isset($order['payWay']) ? $order['payWay'] : 0,
            'order_status'          => 1,
            'pay_sn'                => $order['paySerial'],
            'pay_status'            => 1,
            'pay_time'              => $payTime ? $payTime : $time,
            'pay_money'             => $orderSupplier['real_total_money'],
            'pay_remark'            => '支付成功',
            'apply_response'        => $order['payDecarleResponse']??'',//申报请求响应报文
            'apply_response_time'   => $payTime,
            'apply_request'         => $order['payDecarleRequest']??'',//申报请求报文
            'md'                    => $time,
        ];
        
        //修改下游传入的第三方平台单号
        if (!empty($order['thirdPartOrderSn'])){
            $editSupplierOrder['thirdpart_user_order_sn'] = $order['thirdPartOrderSn'];
        }
        
        //上游需要我们申报好支付单(下游未申报支付单)
        if( $orderSupplier['isUserPayDeclare'] == true ) {
            $editSupplierOrder['is_apply']      = 3;
            $editSupplierOrder['apply_remark']  = "申报中";
            $editSupplierOrder['pay_way']       = 1;
        } else {
            //记录推送订单成功状态
            $editSupplierOrder['order_push_time']   = time();
            $editSupplierOrder['order_push_status'] = 1;
            $editSupplierOrder['order_push_remark'] = "推送订单成功";
        }
        
        if (in_array($orderSupplier['order_type'],OrderPay::YW_ORDER_TYPE_ARR)){
            if (empty($order['logisticNo']) || empty($order['logisticCode']) || empty($order['logisticName']) || empty($order['logisticWayBillContent'])){
                return Normal::returnCode(Normal::FAIL,"自提订单物流参数不能空");
            }
        }
        
        //如果是非刷单模式，在支付的时候写入订单申报资质
        if( empty($orderSupplier['apply_extends']) ) {
            $value = [
                'paySerial'         => $order['paySerial'] ?? '',
                'payCommanyName'    => $order['payCommanyName'] ?? '',
                'payCommanyCode'    => $order['payCommanyCode'] ?? '',
                'enterpriseNum'     => $order['enterpriseNum'] ?? '',
                'enterpriseName'    => $order['enterpriseName'] ?? '',
                'innerTransactionId'=> $order['inner_transaction_id'] ?? '',
                'tracking_number'   => $order['tracking_number'] ?? '',
                'waybill_info'      => $order['waybill_info'] ?? [],
                'IsTransDeclare'    => isset($order['IsTransDeclare']) ? (int)$order['IsTransDeclare'] : 0,
                'logisticNo'        => $order['logisticNo'] ?? '',
                'logisticCode'      => $order['logisticCode'] ?? '',
                'logisticName'      => $order['logisticName'] ?? '',
                'logisticWayBillContent' => $order['logisticWayBillContent'] ?? '',
                'idCardFrontImage'  => $order['idCardFrontImage'] ??'',
                'idCardBackImage'   => $order['idCardBackImage'] ??'',
            ];
            if($orderSupplier['order_source']=='京东'){
                $value['EBCCode']       =   $order['EBCCode'];
                $value['expressCode']   =   $order['expressCode'];
                $value['expressSn']     =   $order['expressSn'];
                $value['PortNo']        =   $order['PortNo'];
            }
            $apply_extends = json_encode($value,JSON_UNESCAPED_UNICODE);
            $editSupplierOrder['apply_extends'] = $apply_extends;
        }
        
        //修改供应商订单表
        $whereSupplierOrder = [
            ['id','=',$orderSupplier['id']],
            ['order_status','in',[0,200]],
            ['is_apply','=',0]
        ];
        $resOrder = OrderSupplier::instance()
        ->where('id',$orderSupplier['id'])
        ->whereIn('order_status',[0,200])
        ->where('is_apply',0)
        ->update($editSupplierOrder);
        if( !$resOrder ) {
            return Normal::returnCode(Normal::FAIL,"供应商订单修改失败");
        }

        return Normal::returnCode(Normal::SUC,"修改成功");
    }

    /**
     * 恢复订单支付状态到支付失败
     * @param array $param
     */
    public function orderChangeRecover( $param = [] )
    {
        $orderSupplier      = $param['supplierOrder'];
        $companyInfo        = $param['companyInfo'];
        $binfo              = $param['binfo'];
        $time               = time();
        $msg                = $param['message'];
        $data = [
            'pay_money'     => 0,
            'md'            => $time,
        ];
        
        //如果是有支付接口的供应商，接口调用失败的情况下，需要进行再次支付，否则进行再次推送订单
        $company_code   = strtolower($companyInfo['company_code']);
        $isReturnSuccess = true;
        if( isset($this->payApiSupplier[$company_code]) ) {
            $data['order_status']   = 200;
            $data['pay_status']     = 0;
            $data['pay_remark']     = "支付失败【{$msg}】";
            $data['md']             = $time;
            $isReturnSuccess = false;
        }
        
        //上游需要刷单，下游未申报
        if( $companyInfo['PayDeclare'] == 1 && $orderSupplier['is_pay_declare'] != 1 && $orderSupplier['order_type'] != 1  ) {
			$data['is_apply']  		= 0;
            $data['apply_remark']   = $msg;
        } else {
            //记录推送订单失败的情况(包括支付失败的情况)
            $data['order_push_status']  = 2;
            $data['order_push_remark']  = $msg;
        }
        
        OrderSupplier::instance()->where('id',$orderSupplier['id'])->update($data);
        return $isReturnSuccess;
    }
}
